/*
 * Enterprise.java
 * 
 * This file is part of Netuno Proteu.
 * 
 * CajuScript is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3, or (at your option) 
 * any later version.
 * 
 * CajuScript is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with CajuScript.  If not, see <http://www.gnu.org/licenses/>.
*/

package org.netuno.proteu;

import java.io.*;
import org.apache.log4j.Logger;
import javax.servlet.*;
import javax.servlet.http.*;
import org.netuno.psamata.script.ScriptRunner;

/**
 * Enterprise.
 * @author eduveks
 */
public class Enterprise extends HttpServlet {
	private static final long serialVersionUID = 1L;
	static Logger logger = Logger.getLogger(Enterprise.class);
    /**
     * Script Folder.
     */
    public static final String SCRIPT_BASE = "WEB-INF/proteu";
    /**
     * Name of script file executed on int.
     */
    public static final String SCRIPT_INIT = "netuno_proteu_init";
    
    /**
     * Name of script file executed on destroy.
     */
    public static final String SCRIPT_DESTROY = "netuno_proteu_destroy";
    /**
     * Name of script file executed on start connection.
     */
    public static final String SCRIPT_START = "netuno_proteu_start";
    /**
     * Name of script file executed on end connection.
     */
    public static final String SCRIPT_END = "netuno_proteu_end";

    private EnterpriseEvents events = null;

    private boolean outputEnabled = true;

    private boolean defaultContentTypeEnabled = true;

    /**
     * Get Enterprise events.
     * @return Events
     */
    public EnterpriseEvents getEvents() {
        return events;
    }

    /**
     * Set Enterprise events.
     * @param events Events
     */
    public void setEvents(EnterpriseEvents events) {
        this.events = events;
    }

    /**
     * If is Output enabled or not.
     * @return Output enabled
     */
    public boolean isOutputEnabled() {
        return outputEnabled;
    }

    /**
     * Set if is Output enabled or not.
     * @param outputEnabled Output enabled
     */
    public void setOutputEnabled(boolean outputEnabled) {
        this.outputEnabled = outputEnabled;
    }

    /**
     * If is default Content-Type enabled or not.
     * @return Default Content-Type enabled
     */
    public boolean isDefaultContentTypeEnabled() {
        return defaultContentTypeEnabled;
    }

    /**
     * Set if is default Content-Type enabled or not.
     * @param defaultContentTypeEnabled Default Content-Type enabled
     */
    public void setDefaultContentTypeEnabled(boolean defaultContentTypeEnabled) {
        this.defaultContentTypeEnabled = defaultContentTypeEnabled;
    }

    /**
     * Servlet init.
     */
    @Override
    public void init() {
        String scriptPath = ScriptRunner.searchFile(getServletContext().getRealPath(SCRIPT_BASE) + File.separator + SCRIPT_INIT);
        Config.setBase(getServletContext().getRealPath(SCRIPT_BASE));
        Config.setBuild(getServletContext().getRealPath("WEB-INF/build"));
        Config.setPublic(getServletContext().getRealPath(""));
        try {
            if (scriptPath != null) {
                ScriptRunner script = new ScriptRunner();
                script.getBindings().put("servlet", this);
                script.runFile(scriptPath);
                try {
                    logger.info("Script \""+ SCRIPT_INIT +"\" executed: "+ scriptPath);
                } catch (Exception e) {}
            }
        } catch (Exception e) {
            try {
                logger.error("Script \""+ SCRIPT_INIT +"\" error: " + scriptPath, e);
            } catch (Exception ex) {}
            throw new Error(e);
        }
    }
    
    /**
     * Servlet destroy.
     */
    @Override
    public void destroy() {
        String scriptPath = ScriptRunner.searchFile(getServletContext().getRealPath(SCRIPT_BASE) + File.separator + SCRIPT_DESTROY);
        try {
            if (scriptPath != null) {
                ScriptRunner script = new ScriptRunner();
                script.getBindings().put("servlet", this);
                script.runFile(scriptPath);
                try {
                    logger.info("Script \""+ SCRIPT_DESTROY +"\" executed: "+ scriptPath);
                } catch (Exception e) {}
            }
        } catch (Exception e) {
            try {
                logger.error("Script \""+ SCRIPT_DESTROY +"\" error: "+ scriptPath, e);
            } catch (Exception ex) {}
            throw new Error(e);
        }
    }
    
    /** 
    * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
    * @param request servlet request
    * @param response servlet response
    */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        logger.info("Proteu Enterprise Start");
        org.netuno.psamata.io.OutputStream out = new org.netuno.psamata.io.OutputStream((OutputStream)response.getOutputStream());
        out.setEnabled(isOutputEnabled());
        boolean error = false;
        Proteu proteu = null;
        try {
            proteu = new Proteu(this, request, response, out);
            out = null;
            try {
                if (getEvents() != null) {
                    getEvents().onStarting(proteu);
                }
            } catch (Exception e) {
                logger.error("Enterprise Event - onStarting", e);
            }
            proteu.getConfig().set("thread_id", ""+ Thread.currentThread().getId());
            proteu.getRequestHead().set("Client", request.getLocalAddr());
            proteu.getRequestAll().set("Client", request.getLocalAddr());
            if (isDefaultContentTypeEnabled()) {
                proteu.getResponseHead().set("Content-Type", "text/html");
            }
            String scriptPath = ScriptRunner.searchFile(Config.getBase() + File.separator + "netuno_proteu_start");
            try {
                if (scriptPath != null) {
                    ScriptRunner script = proteu.getScriptRunner();
                    script.getBindings().put("proteu", proteu);
                    script.getBindings().put("servlet", this);
                    script.getBindings().put("request", request);
                    script.getBindings().put("response", response);
                    script.runFile(scriptPath);
                    logger.info("Script \""+ SCRIPT_START +"\" executed: "+ scriptPath);
                }
            } catch (Throwable t) {
                logger.error("Script \""+ SCRIPT_START +"\" error: "+ scriptPath, t);
                throw new Error(t);
            }
            try {
                if (getEvents() != null) {
                    getEvents().onStarted(proteu);
                }
            } catch (Exception e) {
                logger.error("Enterprise Event - onStarted", e);
            }
            Url.build(proteu);
        } catch (Throwable t) {
            error = true;
            logger.error("Executing", t);
            throw new Error(t);
        } finally {
            try {
                if (getEvents() != null) {
                    getEvents().onEnding(proteu);
                }
            } catch (Throwable t) {
                logger.error("Enterprise Event - onEnding", t);
                throw new Error(t);
            } finally {
                String scriptClosePath = "";
                try {
                    scriptClosePath = ScriptRunner.searchFile(Config.getBase() + File.separator + "netuno_proteu_close");
                    if (scriptClosePath != null && proteu != null) {
                        ScriptRunner script = proteu.getScriptRunner();
                        script.getBindings().put("proteu", proteu);
                        script.getBindings().put("servlet", this);
                        script.getBindings().put("request", request);
                        script.getBindings().put("response", response);
                        script.runFile(scriptClosePath);
                        logger.info("Script \""+ SCRIPT_END +"\" executed: "+ scriptClosePath);
                    }
                } catch (Throwable t) {
                    logger.error("Script \""+ SCRIPT_END +"\": "+ scriptClosePath, t);
                    throw new Error(t);
                } finally {
                    try {
                        Config.setStarting(false);
                        if (proteu != null && proteu.getOutput() != null) {
                            proteu.getOutput().close();
                        }
                    } catch (Throwable t) {
                        logger.error("Closing Proteu output", t);
                        throw new Error(t);
                    } finally {
                        String scriptEndPath = "";
                        try {
                            scriptEndPath = ScriptRunner.searchFile(Config.getBase() + File.separator + "netuno_proteu_end");
                            if (scriptEndPath != null && proteu != null) {
                                ScriptRunner script = proteu.getScriptRunner();
                                script.getBindings().put("proteu", proteu);
                                script.getBindings().put("servlet", this);
                                script.getBindings().put("request", request);
                                script.getBindings().put("response", response);
                                script.runFile(scriptEndPath);
                                logger.info("Script \""+ SCRIPT_END +"\" executed: "+ scriptEndPath);
                            }
                        } catch (Throwable t) {
                            logger.error("Script \""+ SCRIPT_END +"\": "+ scriptEndPath, t);
                            throw new Error(t);
                        } finally {
                            try {
                                if (proteu != null && proteu.getConfig().get("proteu_cache_file") != null) {
                                    ((java.io.File)proteu.getConfig().get("proteu_cache_file")).setReadable(true);
                                }
                            } catch (Throwable t) {
                                logger.error("Cache file set readble.", t);
                                throw new Error(t);
                            } finally {
                                try {
                                    if (error || proteu.getConfig().getBoolean("proteu_cache_delete")) {
                                        Cache.delete(proteu);
                                    }
                                } catch (Throwable t) {
                                    logger.error("Cache delete.", t);
                                    throw new Error(t);
                                } finally {
                                    try {
                                        if (getEvents() != null) {
                                            getEvents().onEnded(proteu);
                                        }
                                    } catch (Throwable t) {
                                        logger.error("Enterprise Event - onEnded", t);
                                        throw new Error(t);
                                    } finally {
                                        try {
                                            if (proteu != null) {
                                                proteu.clear();
                                            }
                                        } finally {
                                            proteu = null;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } 

    /** 
    * Handles the HTTP <code>GET</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
    * Handles the HTTP <code>POST</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
    * Returns a short description of the servlet.
    */
    @Override
    public String getServletInfo() {
        return "Proteu Enterprise";
    }
    
}
